from datetime import datetime, timedelta
from hashlib import md5
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings


router = APIRouter(prefix='/brand', tags=['Brand'])
module_name = '品牌商模块 - 设备管理'


@router.get('/devices', response_model=schemas.BaseApiListOut)
async def index(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    udid: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        设备清单
    """

    objs = OemModel.ExDevice

    if udid:
        objs = objs.where('udid', udid)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'udid', 'like', f'%{keyword}%'
            ).or_where(
                'remarks', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    for item in objs:
        item.register_date = item.register_date.strftime("%Y-%m-%d") if item.register_date else None
        item.start_date = item.start_date.strftime("%Y-%m-%d") if item.start_date else None
        item.end_date = item.end_date.strftime("%Y-%m-%d") if item.end_date else None

    return objs.serialize()


@router.put('/devices/{id}', response_model=schemas.BaseApiOut)
async def put(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    obj = OemModel.ExDevice.where('id', id).first()
    if obj is None:
        return {'code': 1, 'status': 1, 'message': '找不到此设备信息'}

    now = datetime.now()

    # 自动生成注册码相关信息
    try:
        obj.register_date = now.strftime("%Y-%m-%d")
        obj.bill_years = 10
        obj.start_date = now.strftime("%Y-%m-%d")
        obj.end_date = (now + timedelta(days=365 * 10)).strftime("%Y-%m-%d")
        obj.register_code = genRegisterCode(udid=obj.udid, date=now.strftime("%Y-%m-%d"))
        obj.save()
    except Exception as e:
        return {'code': 1, 'status': 1, 'message': f'出错了: {str(e)}'}

    return {'status': 0, 'code': 0, 'message': 'success'}


@router.delete('/devices/{id}', response_model=schemas.BaseApiOut)
async def delete(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    obj = OemModel.ExDevice.where('id', id).first()
    if obj is None:
        return {'code': 1, 'status': 1, 'message': '找不到此设备信息'}

    # 删除注册码相关信息
    try:
        obj.register_date = None
        obj.bill_years = None
        obj.start_date = None
        obj.end_date = None
        obj.register_code = None
        obj.remarks = '手动删除'
        obj.save()
    except Exception as e:
        return {'code': 1, 'status': 1, 'message': f'出错了: {str(e)}'}

    return {'status': 0, 'code': 0, 'message': 'success'}


def genRegisterCode(udid, date):
    register_date = datetime.strptime(date, '%Y-%m-%d')
    headerPrefix = 'eyJhbGciOiJIUzI1NiJ9'

    year = str(register_date.year).zfill(4)
    month = str(register_date.month).zfill(2)

    yearMonth = f'{year}{month}'
    udidYearMonth = f'{udid}{year}{month}'
    print(yearMonth)
    print(udidYearMonth)

    str1 = md5(f'PDA{udid}'.encode('utf-8')).hexdigest()
    str2 = md5(f'{yearMonth}'.encode('utf-8')).hexdigest()
    str3 = md5(f'{udidYearMonth}'.encode('utf-8')).hexdigest()

    udidUdidMd5 = f'{udid}{str3}'
    str4 = md5(f'{udidUdidMd5}'.encode('utf-8')).hexdigest()
    print(udidUdidMd5)

    return f'{headerPrefix}.{str1}{str2}{str3}{str4}'
